<?php

namespace App\Repository;

use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Customer\Grade;
use App\Params\Backend\GradeListParams;
use App\Params\Backend\GradeUpdateParam;
use Illuminate\Support\Facades\Log;

/**
 * 客户等级数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class GradeRepository extends BaseRepository
{
    /**
     * 保存数据
     *
     * @param GradeUpdateParam $param
     * @throws
     * @return int|mixed
     */
    public function save(GradeUpdateParam $param)
    {
        try {
            $query = $param->getGradeId() ? Grade::find($param->getGradeId()) : new Grade();
            foreach ($param as $field => $value) {
                $query->{$field} = $value;
            }
            return $query->save() ? $query->grade_id : 0;
        } catch (\Exception $exception) {
            Log::error("[客户等级] 保存失败：{$exception->getMessage()}");
            throw new BusinessException(ResponseCode::SAVE_FAIL);
        }
    }

    /**
     * 等级列表
     *
     * @param GradeListParams $params
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(GradeListParams $params)
    {
        $query = Grade::query()->orderByDesc('created_at');
        if(!empty($params->getGradeName())) {
            $query->where('grade_name', 'like', '%' . $params->getGradeName() . '%');
        }
        if(!empty($params->getGradeBn())) {
            $query->where('grade_bn', 'like', '%' . $params->getGradeBn() . '%');
        }
        return $query;
    }

    /**
     * 获取会员等级
     *
     * @param int $gradeId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $gradeId)
    {
        return Grade::query()->where('grade_id', $gradeId)->first();
    }
}
